package homework.homework9.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    //请求行相关消息
    private String method;//请求方式
    private String uri;//抽象路径
    private String protocol;//协议版本
    //消息头相关信息
    private Map<String,String> headers = new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;
        //1.1解析请求行
        parseRequestLine();
        //1.2解析消息头
        parseRequestLine();
        //1.3解析消息正文
        parseContent();
    }
    private void parseRequestLine() throws IOException {
        String line = readLine();
        System.out.println("请求行:"+line);

        //indexOf方法中不支持正则表达式
//        method = line.substring(0,line.indexOf(" ")).trim();
//        uri = line.substring(line.indexOf(" "),line.lastIndexOf(" ")).trim();
//        protocol = line.substring(line.lastIndexOf(" ")).trim();

        String[] array = line.split("\\s");
        method = array[0];
        uri = array[1];
        protocol = array[2];
        // http://localhost:8088/myweb/index.html
        System.out.println("method:"+method);    //GET
        System.out.println("uri:"+uri);          // /myweb/index.html
        System.out.println("protocol:"+protocol);//HTTP/1.1
    }

    private void parseHeaders() throws IOException {
        String line;
        while (!(line=readLine()).isEmpty()){
            System.out.println("消息头:"+line);
            String[] array = line.split(":\\s");
            headers.put(array[0],array[1]);
        }
        System.out.println("headers:"+headers);
    }

    private void parseContent(){}

    public String readLine() throws IOException {
        InputStream in =socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char pre='a',cur='a';
        int d;
        while ((d=in.read())!=-1){
            cur = (char) d;
            if (pre==13&&cur==10) {
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name){
        return headers.get(name);
    }
}
